<template>
    <div ref="lineChart" class="line-chart"></div>
</template>

<script>
  import * as echarts from 'echarts';

  export default {
    props: {
      chartData: {
        type: Array,
        required: true,
      },
    },
    mounted() {
      this.initChart();
      window.addEventListener('resize', this.resizeChart);
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.resizeChart);
    },
    methods: {
      initChart() {
        const chartDom = this.$refs.lineChart;
        const myChart = echarts.init(chartDom);

        // 假设 chartData 是一个数组，包含多个系列的数据
        const seriesData = this.chartData.map(data => ({
          name: data.name, // 系列名称
          type: 'line',
          data: data.values, // 对应每个系列的数据
        }));

        const option = {
          title: {
            text: '增长趋势',
          },
          tooltip: {
            trigger: 'axis',
            formatter: (params) => {
              const year = this.chartData[0].labels[params[0].dataIndex];
              let tooltipContent = `${year}<br/>`;
              params.forEach(param => {
                tooltipContent += `${param.seriesName}: ${param.value}<br/>`;
              });
              return tooltipContent;
            },
          },
          xAxis: {
            type: 'category',
            data: this.chartData[0]?.labels || [], // 取第一个系列的标签
            axisLabel: {
              interval: 0,
            },
            axisTick: {
              show: false,
            },
          },
          yAxis: {
            type: 'value',
          },
          series: seriesData,
        };

        myChart.setOption(option);
      },
      resizeChart() {
        const chartDom = this.$refs.lineChart;
        if (chartDom) {
          echarts.getInstanceByDom(chartDom).resize();
        }
      },
    },
  };
</script>

<style scoped>
    .line-chart {
        width: 100%;
        height: 550px; /* 根据需要调整高度 */
    }
</style>
